package com.invengo.module_robot;

import android.app.Application;
import android.text.TextUtils;

import androidx.lifecycle.ProcessLifecycleOwner;

import com.invengo.base.base.IModuleInit;
import com.invengo.library_orionstar.RobotProcessObserver;
import com.invengo.module_robot.ui.weiget.robustwebview.ContextHolder;
import com.invengo.module_robot.ui.weiget.robustwebview.WebViewInitTask;
import com.tencent.smtt.sdk.QbSdk;
import com.tencent.smtt.sdk.TbsListener;

import me.goldze.mvvmhabit.utils.KLog;
import me.goldze.mvvmhabit.utils.cache.ACache;
import me.goldze.mvvmhabit.utils.cache.AKey;
import me.goldze.mvvmhabit.utils.constant.Constants;

public class RobotModuleInit implements IModuleInit {

    @Override
    public boolean onInitAhead(Application application) {
        initX5(application);
        // TODO: 2024/4/10 这个别忘了开
        ProcessLifecycleOwner.get().getLifecycle().addObserver(new RobotProcessObserver(application));
        new Thread(() -> {
            String cacheHost = ACache.getInstance().getAsString(AKey.CACHE_HOST);
            if (TextUtils.isEmpty(cacheHost))
                ACache.getInstance().put(AKey.CACHE_HOST, Constants.DEFAULT_BASE_URL);
        }).start();
        return false;
    }

    @Override
    public boolean onInitLow(Application application) {
        return false;
    }
    private void initWebview(Application application){
        ContextHolder.application = application;
        WebViewInitTask.INSTANCE.init(application);
    }

    private void initX5(Application application){
        QbSdk.setTbsListener(new TbsListener() {
            @Override
            public void onDownloadFinish(int i) {
//                KLog.e("onDownloadFinish: "+i);
            }

            @Override
            public void onInstallFinish(int i) {
                KLog.e("onInstallFinish: "+i);
            }

            @Override
            public void onDownloadProgress(int i) {
                KLog.e("onDownloadProgress: "+i);
            }
        });
        QbSdk.initX5Environment(application, new QbSdk.PreInitCallback() {
            @Override
            public void onCoreInitFinished() {
//                KLog.e("内核初始化完成，可能为系统内核，也可能为系统内核");
                initWebview(application);
                // 内核初始化完成，可能为系统内核，也可能为系统内核
            }

            /**
             * 预初始化结束
             * 由于X5内核体积较大，需要依赖网络动态下发，所以当内核不存在的时候，默认会回调false，此时将会使用系统内核代替
             * @param isX5 是否使用X5内核
             */
            @Override
            public void onViewInitFinished(boolean isX5) {
//                KLog.e("isX5 是否使用X5内核  "+isX5);
            }
        });
    }
}
